<!--
 * @Author: tansq
 * @Date: 2021-09-22 09:37:00
 * @LastEditTime: 2021-09-23 14:12:31
 * @LastEditors: tansq
 * @Description: 附件批量上传
 * @FilePath: \hte-vue-dev\src\components\tools\AttachBatchUpload.vue
 * 可以输入预定的版权声明、个性签名、空行等
-->

<template>
  <div id="attach" style="width: 100%; justify-content: center; display: flex">
    <div style="width: 100%">
      <div>
        <ht-upload
          ref="myUpload"
          multiple
          :dbKey="dbKey"
          :busField="busField"
          :busType="busType"
          :busKey="busKey"
          :ftpKey="ftpKey"
          v-model="fileList"
          :before-upload="beforeUpload"
           :accept="accept"
          :show-file-list="false"
        >
          <a-button slot="trigger" icon="upload">新增附件</a-button>
          <a-button style="margin-left: 10px; margin-bottom: 10px" icon="delete" @click="deleteAttach"> 删除 </a-button>
        </ht-upload>
      </div>
      <div>
        <a-table
          :columns="columns"
          :data-source="fileList"
          rowKey="id"
          bordered
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          @change="handleTableChange"
          :pagination="ipagination"
        >
          <span slot="fileName" slot-scope="text, record">
            <a icon="download" @click="handlePreview(record)">{{ text }}</a>
          </span>

        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import '@/config/upload.install.js';
import { getAction,postAction,previewAttach } from '@/api/manage';
import { formatFileSize, endWith } from '@/utils/common.js'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
// import * as localStorage from '@/utils/localStorage';
// import * as RequestHost from '@/api/env';

const columns = [
  {
    title: '附件名称',
    dataIndex: 'fileName',
    key: 'fileName',
    scopedSlots: { customRender: 'fileName' }
  },
  {
    title: '文件大小',
    dataIndex: 'size',
    key: 'size'
  },
  {
    title: '上传时间',
    dataIndex: 'uploadTime',
    key: 'uploadTime'
  }
];
export default {
  components: {},
  props: {
    accept:{
      type:String,
     default:'*',
     required:false,
    },
   dbKey:{
     type:String,
     default:'Trd',
     required:false,
   },
    busField:{
     type:String,
     default:'attachBatchUpload',
     required:false,
   },
   busType:{
     type:String,
     default:'1',
     required:false,
   },
   busKey:{
     type:String,
     default:null,
     required:false,
   },
   ftpKey:{
     type:String,
     default:'ftp',
     required:false,
   },
   
  },
  data() {
    return {
      columns,
      fileList: [],
     
      selectedRowKeys: [],
      url: {
        deleteBatch:'/common/deleteBatch'
      },
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '30', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条';
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      }
    };
  },
  created() {
    
  },
  methods: {
    /**
     * 表结构切换页码
     */
    handleTableChange(pagination, filters, sorter) {
      this.ipagination = pagination;
      this.ipagination.pageNo = this.ipagination.current;
    },


    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    deleteAttach() {
     
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请选中要删除的附件');
        return false;
      }
      let attachIds = [];
      this.selectedRowKeys.forEach(element => {
        attachIds.push(element);
      });

      const that = this;
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中附件?',
        onOk: function() {
          getAction(that.url.deleteBatch,{attachIds:attachIds.join(","),ftpKey:that.ftpKey,dbKey:that.dbKey}).then(res=>{
            if(res.code == 1){
                  
              that.selectedRowKeys.forEach(key => {
                const idx = that.fileList.findIndex((value)=>value.id==key)
                that.fileList.splice(idx,1);
              });

            }
          })

        }
      });
    },
    deleteAall(){
      const that = this;
      let attachIds = []
      this.fileList.map(item=>{
        attachIds.push(item.id)
      })
      getAction(that.url.deleteBatch,{attachIds:attachIds.join(","),ftpKey:that.ftpKey,dbKey:that.dbKey}).then(res=>{
        if(res.code == 1){
              
          that.fileList = [];

        }
      })
    },
    beforeUpload(file){
      let fileName= file.fileName 
      let fileNameMore = this.fileList.find(item=>{
        return item.fileName == fileName
      })
      if(!!fileNameMore){
        that.$message.success(`${fileName}文件名重复`);
        return false
      }
    },
    handlePreview(file) {
      let that = this
      if (
        endWith(file.fileName, 'rar') ||
        endWith(file.fileName, 'zip') ||
        endWith(file.fileName, 'dwg') ||
        endWith(file.fileName, 'tgz')
      ) {
        
        return true
      }
      let params={
        id:file.id,
        ftpKey:that.ftpKey
      };
      previewAttach(params).then(result=>{
        const url=URL.createObjectURL(result)
        window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },

  },
};
</script>

<style>
.el-upload__input {
  display: none;
}
.el-upload {
  display: inline-block;
  text-align: center;
  cursor: pointer;
  outline: 0;
}
</style>
